package com.jams.goodox.net;

import android.content.Context;
import android.util.Log;

import com.jams.goodox.BuildConfig;
import com.jams.goodox.R;
import com.jams.goodox.utils.DialogUtils;
import com.jams.goodox.utils.ToastUtil;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 *
 * Created by Computer on 2017/4/14.
 */

 public abstract class RetrofitCallBacks<T extends BaseEntity> implements Callback<T> {
    Context context;


    public RetrofitCallBacks(Context context) {
        this.context = context;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if(call.isCanceled())return;
        if (response != null && response.isSuccessful() && response.body() != null) {
            if (("200").equalsIgnoreCase(response.body().code)) {
                onSuccess(response);
            } else {//status 非"100"
                switch (String.valueOf(response.body().status)) {
                    case "102":
                        onFail(response.body().msg);
                        DialogUtils.showTokenMiss(context,response.body().msg);
                        break;
                    case "106":
                        //ToastUtil.show(response.body().msg);
                        onFail(response.body().msg);
                        unSuccessStatus(response.body().status, response.body().msg);
                        break;
                    default:
                        //ToastUtil.show(response.body().msg);
                        onFail(response.body().msg);
                        unSuccessStatus(response.body().status, response.body().msg);
                        break;
                }
            }
        } else {
            onFailure(call, new RuntimeException("response error,detail = " + (response != null ? response.raw().toString() : null)));
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        try {
            if(BuildConfig.DEBUG){
                Log.i("RetrofitCallBacks",t.getMessage());
            }
        } catch (Exception e) {

        }
        if (call != null && !call.isCanceled()){
            onFail(context.getString(R.string.net_request_fail));
        }
    }

    public abstract void onSuccess(Response<T> response); //成功

    public abstract void onFail(String message); // 失败

    public abstract void unSuccessStatus(String status, String message); // status非100的情况
}
